package com.xiaowu.house.user.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.xiaowu.house.config.service.ISysDictionaryService;
import com.xiaowu.house.domain.ResultCode;
import com.xiaowu.house.domain.dto.LoginUserDTO;
import com.xiaowu.house.domain.dto.TokenDTO;
import com.xiaowu.house.exception.ServiceException;
import com.xiaowu.house.service.TokenService;
import com.xiaowu.house.user.domain.dto.PasswordLoginDTO;
import com.xiaowu.house.user.domain.dto.SysUserDTO;
import com.xiaowu.house.user.domain.dto.SysUserListReqDTO;
import com.xiaowu.house.user.domain.dto.SysUserLoginDTO;
import com.xiaowu.house.user.domain.entity.SysUser;
import com.xiaowu.house.user.mapper.SysUserMapper;
import com.xiaowu.house.user.service.ISysUserService;
import com.xiaowu.house.utils.AESUtil;
import com.xiaowu.house.utils.VerifyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class SysUserServiceImpl implements ISysUserService {


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDictionaryService sysDictionaryService;


    @Override
    public TokenDTO login(PasswordLoginDTO passwordLoginDTO) {
        LoginUserDTO loginUserDTO = new LoginUserDTO();

        if (!VerifyUtil.checkPhone(passwordLoginDTO.getPhone())) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "手机号不合理");
        }

        SysUser sysUser = sysUserMapper.selectByPhoneNumber(
                AESUtil.encryptHex(passwordLoginDTO.getPhone()));
        if (sysUser == null) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "手机号不存在");
        }

        String password = AESUtil.decryptHex(passwordLoginDTO.getPassword());
        String passwordEncrypt = DigestUtil.sha256Hex(password);
        // 拿加密后的密码与数据库字段比较
        if (!passwordEncrypt.equals(sysUser.getPassword())) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "密码不正确");
        }
        // 3 校验用户状态
        if (sysUser.getStatus().equals("disable")) {
            throw new ServiceException(ResultCode.USER_DISABLE);
        }

        // 4 设置登录信息
        loginUserDTO.setUserId(sysUser.getId());
        loginUserDTO.setUserName(sysUser.getNickName());
        loginUserDTO.setUserFrom("sys");

        return tokenService.createToken(loginUserDTO);
    }

    @Override
    public Long addOrEdit(SysUserDTO sysUserDTO) {

        SysUser sysUser = new SysUser();

        if (sysUserDTO.getUserId() == null) {
            if (StringUtils.isEmpty(sysUserDTO.getPassword()) || !sysUserDTO.checkPassword()) {
                throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "密码校验失败");
            }

            if (!VerifyUtil.checkPhone(sysUserDTO.getPhoneNumber())) {
                throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "手机号校验失败");
            }

            SysUser existSysUser = sysUserMapper.selectByPhoneNumber(sysUserDTO.getPhoneNumber());
            if (existSysUser != null) {
                throw new ServiceException( ResultCode.INVALID_PARA.getCode(), "手机号已存在");
            }

            if (StringUtils.isEmpty(sysUserDTO.getIdentity()) ||
                    sysDictionaryService.getDicDataByKey(sysUserDTO.getIdentity()) == null) {
                throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "用户身份错误");
            }

            sysUser.setPhoneNumber(
                    AESUtil.decryptHex(sysUserDTO.getPhoneNumber())
            );
            sysUser.setPassword(
                    DigestUtil.sha256Hex(sysUserDTO.getPassword())
            );
            sysUser.setIdentity(sysUserDTO.getIdentity());
        }
        sysUser.setId(sysUserDTO.getUserId());
        sysUser.setNickName(sysUserDTO.getNickName());

        if (sysDictionaryService.getDicDataByKey(sysUserDTO.getStatus()) == null) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "用户状态错误");
        }
        sysUser.setStatus(sysUserDTO.getStatus());
        sysUser.setRemark(sysUserDTO.getRemark());

        sysUserMapper.insertOrUpdate(sysUser);

        if (sysUserDTO.getUserId() != null && sysUserDTO.getStatus().equals("disable")) {
            tokenService.delLoginUser(sysUserDTO.getUserId(), "sys");
        }
        return sysUser.getId();
    }

    @Override
    public List<SysUserDTO> getUserList(SysUserListReqDTO sysUserListReqDTO) {
        SysUser searchSysUser = new SysUser();
        searchSysUser.setPhoneNumber(
                AESUtil.decryptHex(sysUserListReqDTO.getPhoneNumber())
        );
        searchSysUser.setStatus(sysUserListReqDTO.getStatus());
        searchSysUser.setId(sysUserListReqDTO.getUserId());

        List<SysUser> sysUserList = sysUserMapper.selectList(searchSysUser);

        return sysUserList.stream()
                .map(sysUser -> {
                    SysUserDTO sysUserDTO = new SysUserDTO();
                    sysUserDTO.setNickName(sysUser.getNickName());
                    sysUserDTO.setStatus(sysUser.getStatus());
                    sysUserDTO.setUserId(sysUserDTO.getUserId());
                    sysUserDTO.setRemark(sysUserDTO.getRemark());
                    sysUserDTO.setPhoneNumber(
                            AESUtil.decryptHex(sysUserDTO.getPhoneNumber())
                    );
                    sysUserDTO.setIdentity(sysUser.getIdentity());
                    return sysUserDTO;
                }).collect(Collectors.toList());
    }

    @Override
    public SysUserLoginDTO getLoginUser() {
        LoginUserDTO loginUserDTO = tokenService.getLoginUser();

        if (loginUserDTO == null || loginUserDTO.getUserId() == null) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "用户令牌有误");
        }

        SysUser sysUser = sysUserMapper.selectById(loginUserDTO.getUserId());
        if (sysUser == null ) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "用户不存在");
        }
        SysUserLoginDTO sysUserLoginDTO = new SysUserLoginDTO();
        BeanUtils.copyProperties(loginUserDTO, sysUserLoginDTO);
        BeanUtils.copyProperties(sysUser, sysUserLoginDTO);
        return sysUserLoginDTO;
    }
}
